﻿using UnityEngine;
using UnityEngine.UI;

namespace JH
{
    /// <summary>
    ///  基础的Toggle事件
    /// </summary>
    [RequireComponent(typeof(Toggle))]
    public abstract class BaseToggleCustomEvent : MonoBehaviour, IToggleEvent
    {
        /// <summary>
        ///  是否反向
        /// </summary>
        [field: SerializeField, Header("反转事件")]
        public bool IsReverse { get; set; }

        /// <summary>
        ///  toggle
        /// </summary>
        [SerializeField, HideInInspector] protected Toggle toggle;

        private void OnEnable()
        {
            toggle.onValueChanged.AddListener(OnToggleValueChanged);
        }

        private void OnDisable()
        {
            toggle.onValueChanged.RemoveListener(OnToggleValueChanged);
        }

        protected virtual void OnValidate()
        {
            if (toggle == null) toggle = GetComponent<Toggle>();
        }

        public void OnToggleValueChanged(bool isOn)
        {
            if (isOn)
            {
                if (IsReverse)  OnToggleOff();
                else OnToggleOn();
            }
            else
            {
                if (IsReverse) OnToggleOn();
                else OnToggleOff();
            }
        }

        /// <summary>
        ///  toggle打开时
        /// </summary>
        protected virtual void OnToggleOn()
        {
        }

        /// <summary>
        ///  toggle关闭时
        /// </summary>
        protected virtual void OnToggleOff()
        {
        }
    }
}